<template>
  <ContentDetailWrap :title="t('warehouse.add')">
    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
      <BaseButton type="primary" :loading="loading" @click="submit(formRef)">
        {{ t('action.save') }}
      </BaseButton>
    </template>
    <!--    表单-->
    <el-form :model="state.form" ref="formRef" :rules="rules as FormRules" label-width="180px">
      <el-form-item :label="t('invoice.invoice_no')" class="w-60%">
        <el-input
          v-model="state.form.invoice_no"
          disabled
          :placeholder="'请输入' + t('invoice.invoice_no')"
        />
      </el-form-item>
      <el-form-item :label="t('invoice.applicant')" class="w-60%" prop="applicant" required>
        <el-input
          v-model="state.inputDisplayText.applicant"
          disabled
          :placeholder="'请选择' + t('invoice.applicant')"
        >
          <template #append>
            <el-button size="small" text type="primary" @click="handleOpenOperator">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item :label="t('invoice.customer_id')" class="w-60%" prop="customer_id" required>
        <el-input
          v-model="state.inputDisplayText.customer_name"
          disabled
          :placeholder="'请选择' + t('invoice.customer_id')"
        >
          <template #append>
            <el-button size="small" text type="primary" @click="handleOpenCustomer">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
      <!-- <el-form-item :label="t('invoice.order_type')" class="w-60%" prop="order_type" required>
        <el-select
          v-model="state.form.order_type"
          :placeholder="'请选择' + t('invoice.order_type')"
        >
          <el-option
            v-for="item in state.orderTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item :label="t('invoice.order_id')" class="w-60%" prop="order_id" required>
        <el-input
          v-model="state.inputDisplayText.order_id"
          disabled
          :placeholder="'请选择' + t('invoice.order_id')"
        >
          <template #append>
            <el-button size="small" text type="primary" @click="handleOpenOrder">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item :label="t('invoice.payment_ids')" class="w-60%" prop="payment_ids" required>
        <el-input
          v-model="state.inputDisplayText.payment_ids"
          disabled
          :placeholder="'请选择' + t('invoice.payment_ids')"
        >
          <template #append>
            <el-button size="small" text type="primary" @click="handleOpenOrderPayment"
              >选择</el-button
            >
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        :label="t('invoice.invoicing_date')"
        class="w-60%"
        prop="invoicing_date"
        required
      >
        <el-date-picker
          v-model="state.form.invoicing_date"
          type="date"
          :placeholder="'请选择' + t('invoice.invoicing_date')"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item :label="t('invoice.tax_refund')" class="w-60%" prop="tax_refund" required>
        <el-select
          v-model="state.form.tax_refund"
          :placeholder="'请选择' + t('invoice.tax_refund')"
        >
          <el-option label="否" :value="0" />
          <el-option label="是" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item
        :label="t('invoice.taxrefund_amount')"
        class="w-60%"
        v-show="state.form.tax_refund"
        prop="taxrefund_amount"
      >
        <el-input
          v-model="state.form.taxrefund_amount"
          type="number"
          :placeholder="'请输入' + t('invoice.taxrefund_amount')"
        />
      </el-form-item>
      <el-form-item
        :label="t('invoice.invoice_amount')"
        class="w-60%"
        prop="invoice_amount"
        required
      >
        <el-input
          v-model.number="state.form.invoice_amount"
          type="number"
          :placeholder="'请输入' + t('invoice.invoice_amount')"
        />
      </el-form-item>

      <el-form-item :label="t('invoice.invoice_type')" class="w-60%" prop="invoice_type" required>
        <el-select
          v-model="state.form.invoice_type"
          :placeholder="'请选择' + t('invoice.invoice_type')"
        >
          <el-option
            v-for="item in state.invoiceTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('invoice.remark')" class="w-60%" prop="remark">
        <el-input
          v-model="state.form.remark"
          :placeholder="'请输入' + t('invoice.remark')"
          type="textarea"
        />
      </el-form-item>
      <el-form-item
        :label="t('invoice.attach')"
        :placeholder="'请输入' + t('invoice.attach')"
        class="w-60%"
      >
        <UploadFile
          url="/common/uploadFile"
          drag
          :file-type="['png', 'jpg', 'jpeg', 'bmp', 'pdf', 'docx', 'doc', 'xlsx', 'xls']"
          :params="{ directory: 11 }"
          :limit="9"
          upload-file-button-name="点击上传或拖拽到此处上传"
          buttonWidth="100%"
          :button-link="true"
          :show-file-list="true"
          @upload-success-res="handleUploadCallback"
          @handle-remove-file="handleRemoveFile"
          @handle-picture-card-preview="handlePictureCardPreview"
        />
      </el-form-item>
      <el-form-item :label="t('invoice.invoice_info')">
        <!--      table-->
        <el-table
          :data="tableData"
          border
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }"
          @current-change="handleSelectionChange"
        >
          <el-table-column width="60">
            <template #default="{ row }">
              <el-radio v-model="state.currentInvoiceTableRowKey" :label="row.id" />
            </template>
          </el-table-column>
          <el-table-column :label="t('invoice.invoice_header')">
            <template #default="{ row }">
              <el-input
                v-model="row.invoice_header"
                type="invoice_header"
                :placeholder="t('invoice.invoice_header')"
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column :label="t('invoice.tax_id_num')">
            <template #default="{ row }">
              <el-input v-model="row.tax_id_num" :placeholder="t('invoice.tax_id_num')" clearable />
            </template>
          </el-table-column>
          <el-table-column :label="t('invoice.register_phone')">
            <template #default="{ row }">
              <el-input
                v-model="row.register_phone"
                :placeholder="t('invoice.register_phone')"
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column :label="t('invoice.billing_address')">
            <template #default="{ row }">
              <el-input
                v-model="row.billing_address"
                :placeholder="t('invoice.billing_address')"
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column :label="t('invoice.opening_bank')">
            <template #default="{ row }">
              <el-input
                v-model="row.opening_bank"
                :placeholder="t('invoice.opening_bank')"
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column :label="t('invoice.opening_account')">
            <template #default="{ row }">
              <el-input
                v-model="row.opening_account"
                :placeholder="t('invoice.opening_account')"
                clearable
              />
            </template>
          </el-table-column>
          <!-- <el-table-column :label="t('purchase.logistics.operation')" width="300">
            <template #default="{ row, $index }">
              <el-button type="primary" @click="handleSave(row)" class="m-r-5">
                {{ t('purchase.logistics.save') }}
              </el-button>
              <el-button type="primary" :icon="Plus" circle @click="handleAdd" class="m-r-2" />
              <el-button type="danger" :icon="Delete" circle @click="handleDelete(row, $index)" />
            </template>
          </el-table-column> -->
        </el-table>
      </el-form-item>
    </el-form>
  </ContentDetailWrap>
  <!--  选择申请人弹框-->
  <DialogOperatorChecked
    ref="DialogOperatorCheckedRef"
    @expose-multiple-data="getExposeOperatorData"
  />
  <!--  选择客户弹框-->
  <DialogCustomerChecked
    ref="DialogCustomerCheckedRef"
    @expose-multiple-data="getExposeCustomerData"
  />
  <!--  选择订单弹框-->
  <DialogOrderChecked
    ref="DialogOrderCheckedRef"
    @expose-multiple-data="getExposeOrderData"
    :multiple="true"
  />

  <!--  选择支付订单弹框-->
  <DialogOrderPaymentChecked
    ref="DialogOrderPaymentCheckedRef"
    :multiple="true"
    @expose-multiple-data="getExposeOrderPaymentData"
  />
</template>
<script setup lang="ts">
import dayjs from 'dayjs'
import DialogCustomerChecked from '../../Customer/Customer/components/DialogChecked/index.vue'
import DialogOperatorChecked from '../../Authorization/Operator/components/DialogChecked/index.vue'
import DialogOrderChecked from '../Order/components/DialogChecked/index.vue'
import DialogOrderPaymentChecked from '../OrderPayment/components/DialogChecked/index.vue'

import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ElMessage, ElMessageBox, ElLoading, type FormRules, type FormInstance } from 'element-plus'
import { getEnumApi, saveDataApi } from '@/api/invoice'
import { CurdData } from '@/api/invoice/types'
import { createImageViewer } from '@/components/ImageViewer'
import { getListApi as getInvoicingInfoListApi } from '@/api/invoicingInfo'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import { CurdData as invoicingInfoCurdData } from '@/api/invoicingInfo/types'

const { t } = useI18n()
const { push, go } = useRouter()
const route = useRoute()
const userStore = useUserStore()

const loading = ref<boolean>(false)
const formRef = ref<FormInstance>()
const state = reactive({
  source: route.query.source ? decodeURIComponent(route.query.source as string) : '',
  // 订单类型列表
  orderTypeList: ref<Array<Record<string, any>>>([]),
  // 发票类型列表
  invoiceTypeList: ref<Array<Record<string, any>>>([]),
  // 输入显示文本
  inputDisplayText: {
    // 申请人
    applicant: '',
    // 客户ID显示名称
    customer_name: route.query.cusname as string,
    // 订单ID
    order_id: '',
    // 支付ID
    payment_ids: '',
    max_nvoice_amount: 0
  },
  form: ref<any>({
    invoice_no: '',
    applicant: 0,
    customer_id: Number(route.query.customer_id) || 0,
    order_id: '',
    order_type: '',
    invoicing_date: '',
    payment_ids: '',
    remark: '',
    attach: '',
    invoice_attach: '',
    invoice_type: 2,
    tax_refund: 0,
    invoice_header: '',
    tax_id_num: '',
    register_phone: '',
    billing_address: '',
    opening_bank: '',
    opening_account: ''
  }),
  currentInvoiceTableRow: ref<invoicingInfoCurdData>({
    invoice_header: '',
    tax_id_num: ''
  }), // 当前发票表格行数据
  currentInvoiceTableRowKey: ref<number>(0), // 当前发票表格行键
  attachList: ref<any[]>([]) // 附件列表
})

const tableData = ref<Array<Record<string, any>>>([]) // 表格数据

const rules = ref<FormRules>({
  applicant: [
    {
      required: true,
      message: '请选择' + t('invoice.applicant'),
      trigger: 'change'
    }
  ],
  customer_id: [
    {
      required: true,
      message: '请选择' + t('invoice.customer_id'),
      trigger: 'change'
    }
  ],
  order_type: [
    {
      required: true,
      message: '请选择' + t('invoice.order_type'),
      trigger: 'change'
    }
  ],
  order_id: [
    {
      required: true,
      message: '请选择' + t('invoice.order_id'),
      trigger: 'change'
    }
  ],
  payment_ids: [
    {
      required: true,
      message: '请选择' + t('invoice.payment_ids'),
      trigger: 'change'
    }
  ],
  invoicing_date: [
    {
      required: true,
      message: '请选择' + t('invoice.invoicing_date'),
      trigger: 'change'
    }
  ],
  invoice_amount: [
    {
      required: true,
      message: '请输入' + t('invoice.invoice_amount'),
      trigger: 'change'
    }
  ],
  invoice_type: [
    {
      required: true,
      message: '请选择' + t('invoice.invoice_type'),
      trigger: 'change'
    }
  ],
  taxrefund_amount: [
    {
      required: Boolean(state.form.tax_refund), // 根据 tax_refund 动态设置是否必填
      message: '请输入' + t('invoice.taxrefund_amount'),
      trigger: 'change'
    }
  ]
})

const DialogOperatorCheckedRef = ref<InstanceType<typeof DialogOperatorChecked>>() // 定义弹框引用
const DialogCustomerCheckedRef = ref<InstanceType<typeof DialogCustomerChecked>>()
// const DialogWholesaleOrderCheckedRef = ref<InstanceType<typeof DialogWholesaleOrderChecked>>()
const DialogOrderCheckedRef = ref<InstanceType<typeof DialogOrderChecked>>()
const DialogOrderPaymentCheckedRef = ref<InstanceType<typeof DialogOrderPaymentChecked>>()

//打开选择申请人弹框
const handleOpenOperator = () => {
  nextTick(() => {
    console.log('state.form.applicant', state.form.applicant)
    DialogOperatorCheckedRef!.value!.dialogVisible = true
    DialogOperatorCheckedRef!.value!.initialize(
      state.form.applicant ? [{ id: state.form.applicant }] : []
    )
  })
}

//打开选择客户弹框
const handleOpenCustomer = () => {
  nextTick(() => {
    DialogCustomerCheckedRef!.value!.dialogVisible = true
    DialogCustomerCheckedRef!.value!.initialize(
      state.form.customer_id ? [{ id: state.form.customer_id }] : []
    )
  })
}

//打开选择订单弹框
const handleOpenOrder = () => {
  if (1 > state.form.customer_id) {
    ElMessage.warning('请先选择关联客户') //如果客户id小于等于0，则提示请先选择关联客户
    return
  }

  nextTick(() => {
    DialogOrderCheckedRef!.value!.dialogVisible = true //如果订单类型为order，则打开选择订单弹框
    let val = []
    if (state.form.order_id) {
      val = state.form.order_id.split(',').map((v, vIndex) => {
        return {
          id: v,
          order_no: state.inputDisplayText.order_id.split(',')[vIndex]
        }
      })
    }
    DialogOrderCheckedRef!.value!.initialize(
      val,
      String(state.inputDisplayText.customer_name),
      true,
      state.orderTypeList
    )
  })
}

//打开选择付款单弹框
const handleOpenOrderPayment = () => {
  if (!state.form.order_id) {
    ElMessage.warning('请先选择关联订单')
    return
  }
  nextTick(() => {
    DialogOrderPaymentCheckedRef!.value!.dialogVisible = true
    DialogOrderPaymentCheckedRef!.value!.initialize(
      state.form.payment_ids
        ? state.form.payment_ids.split(',').map((item) => ({ id: Number(item.trim()) }))
        : [],
      state.inputDisplayText.order_id,
      state.form.order_id,
      true
    )
  })
}

//上传成功以后回调
const handleUploadCallback = (val: any) => {
  state.attachList.push(val)
  console.log(state.attachList)
}

const handleRemoveFile = (val: any) => {
  if (state.attachList && state.attachList.length) {
    state.attachList = state.attachList.filter((item: Record<string, any>) => {
      item.uploadFile.uid !== val.uid
    })
  }
}

const handlePictureCardPreview = (val: any) => {
  if (!val) return
  createImageViewer({
    urlList: [val],
    zIndex: 99999
  })
}

//接收勾选中的申请人
const getExposeOperatorData = (val: any[]) => {
  if (!val || !val.length) return
  if (state.form.applicant && state.form.applicant !== val[0].id) {
  }
  state.form.applicant = val[0].id
  state.inputDisplayText.applicant = val[0].cname
}

//接收勾选中的客户
const getExposeCustomerData = (val: any[]) => {
  if (!val || !val.length) return
  if (state.form.customer_id && state.form.customer_id !== val[0].id) {
  }
  state.form.customer_id = val[0].id
  state.inputDisplayText.customer_name = val[0].cusname
  getInvoicingInfoList()
}

//接收勾选中的普通订单
const getExposeOrderData = (val: any[], order_type: string) => {
  if (!val || !val.length) return
  // if (state.form.order_id && state.form.order_id !== val[0].id) {
  //   state.form.payment_ids = ''
  //   state.form.invoice_amount = 0
  //   state.inputDisplayText.max_nvoice_amount = 0
  //   state.inputDisplayText.payment_ids = ''
  // }
  // state.form.order_type = order_type
  // state.form.order_id = val[0].id
  // state.inputDisplayText.order_id = val[0].order_no
  let orderNoList = val.filter((item: any) => item.order_no)
  state.form.order_id = orderNoList.map((item: any) => item.id).join(',')
  state.inputDisplayText.order_id = orderNoList.map((item: any) => item.order_no).join(',')
  console.log(state.form.order_type)
  // 关联订单修改，则付款单清空，重新选择
  getExposeOrderPaymentData([])
}

//接收勾选中的支付订单
const getExposeOrderPaymentData = (val: any[]) => {
  // if (!val || !val.length) return
  // if (state.form.payment_ids) {
  // }
  // state.form.payment_ids = val.map((item: any) => item.id).join(',')
  // state.form.invoice_amount = val.reduce((acc, item) => {
  //   return acc + Number(item.paid_amount)
  // }, 0)
  // state.inputDisplayText.max_nvoice_amount = state.form.invoice_amount ?? 0
  // state.inputDisplayText.payment_ids = val.map((item: any) => item.id).join(',')
  let orderNoList = val.filter((item: any) => item.id)
  state.form.payment_ids = orderNoList.map((item: any) => item.id).join(',')
  state.inputDisplayText.payment_ids = orderNoList.map((item: any) => item.id).join(',')
  state.form.invoice_amount = orderNoList.reduce((acc, item) => {
    return acc + Number(item.paid_amount)
  }, 0)
  state.inputDisplayText.max_nvoice_amount = state.form.invoice_amount ?? 0
}

// 处理当前行变化事件
const handleSelectionChange = (currentRow) => {
  console.log(currentRow)
  if (currentRow) {
    // 设置当前选中行的 key
    state.currentInvoiceTableRowKey = currentRow.id
    state.currentInvoiceTableRow = currentRow
    state.form.invoice_header = currentRow.invoice_header
    state.form.tax_id_num = currentRow.tax_id_num
    state.form.invoice_header = currentRow.register_phone
    state.form.billing_address = currentRow.billing_address
    state.form.opening_bank = currentRow.opening_bank
    state.form.opening_account = currentRow.opening_account
  }
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getEnumApi({ field: 'all' })
  state.orderTypeList = resp.data.order_type
  state.invoiceTypeList = resp.data.invoice_type
  state.form.invoice_no = resp.data.invoice_no
}

const getInvoicingInfoList = async () => {
  const resp = await getInvoicingInfoListApi({
    customer_id: state.form.customer_id
  })
  tableData.value = resp.data.list
  if (!Array.isArray(tableData.value)) {
    tableData.value = [] // 如果不是数组，则初始化为空数组
  }
  // 然后判断数组长度
  if (tableData.value.length === 0) {
    tableData.value.push({
      id: 1,
      invoice_header: '',
      tax_id_num: '',
      register_phone: '',
      billing_address: '',
      opening_bank: '',
      opening_account: ''
    })
  }
  if (resp.data.list && resp.data.list.length > 0) {
    state.currentInvoiceTableRowKey = resp.data.list[0]?.id
    state.currentInvoiceTableRow = resp.data.list[0]
    state.form.invoice_header = resp.data.list[0]?.invoice_header
    state.form.tax_id_num = resp.data.list[0]?.tax_id_num
    state.form.register_phone = resp.data.list[0]?.register_phone
    state.form.billing_address = resp.data.list[0]?.billing_address
    state.form.opening_bank = resp.data.list[0]?.opening_bank
    state.form.opening_account = resp.data.list[0]?.opening_account
  }
}

const dynamicallySelectData = () => {
  // 动态选择数据
  state.form.applicant = userStore.getUserInfo?.id ?? 0
  state.inputDisplayText.applicant = userStore.getUserInfo?.username ?? ''

  state.form.customer_id = route.query.customer_id ? Number(route.query.customer_id) : 0
  state.inputDisplayText.customer_name = route.query.cusname ? String(route.query.cusname) : ''
  // 关联订单赋值
  state.form.order_id = route.query.order_id ? Number(route.query.order_id) : 0
  state.form.order_type = route.query.order_type ? String(route.query.order_type) : 'order'
  state.inputDisplayText.order_id = route.query.order_no ? String(route.query.order_no) : ''

  state.form.invoicing_date = dayjs().format('YYYY-MM-DD')
}

const submit = async (formEl: FormInstance | undefined) => {
  console.log(state.currentInvoiceTableRow?.invoice_header)
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      if (!state.form.applicant) return ElMessage.warning('请选择' + t('invoice.applicant'))
      if (!state.form.customer_id) return ElMessage.warning('请选择' + t('invoice.customer_id'))
      if (!state.form.order_id) return ElMessage.warning('请选择' + t('invoice.order_id'))
      if (!state.form.payment_ids) return ElMessage.warning('请选择' + t('invoice.payment_ids'))

      if (state.form.tax_refund && !state.form.taxrefund_amount)
        return ElMessage.warning('请输入' + t('invoice.taxrefund_amount'))

      if (!state.currentInvoiceTableRow.invoice_header) {
        return ElMessage.warning('请编辑' + t('invoice.invoice_header'))
      } else {
        state.form.invoice_header = state.currentInvoiceTableRow.invoice_header
      }
      if (!state.currentInvoiceTableRow.tax_id_num) {
        return ElMessage.warning('请编辑' + t('invoice.tax_id_num'))
      } else {
        state.form.tax_id_num = state.currentInvoiceTableRow.tax_id_num
      }

      if (
        state.form.invoice_amount &&
        state.form.invoice_amount > state.inputDisplayText.max_nvoice_amount
      )
        return ElMessage.warning('发票金额不能大于支付金额')
      if (state.attachList.length > 0)
        state.form.attach = state.attachList.map((item) => item.id).join(',')
      state.form.invoicing_date = dayjs().format('YYYY-MM-DD')
      state.form.register_phone = state.currentInvoiceTableRow.register_phone ?? ''
      state.form.billing_address = state.currentInvoiceTableRow.billing_address ?? ''
      state.form.opening_bank = state.currentInvoiceTableRow.opening_bank ?? ''
      state.form.opening_account = state.currentInvoiceTableRow.opening_account ?? ''
      const params = { ...state.form } as unknown as Record<string, any>

      const resp = await saveDataApi(params)
      if (resp.code === 0) {
        ElMessage.success(t('order.createSucMsg'))
        if (state.source) {
          push(`${state.source}`)
        } else {
          push('/order/invoice-management')
        }
      }
    }
  })
}

onMounted(() => {
  getDropDownBoxInfo()
  getInvoicingInfoList()
  dynamicallySelectData()
})
</script>

<style lang="less" scoped>
/* 隐藏 el-radio 的文本标签 */
:deep(.el-radio__label) {
  display: none;
}
</style>
